package com.ge.med.cchelper.popup.actions;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.ge.med.cchelper.Constants;
import com.ge.med.cchelper.bean.CSession;
import com.ge.med.cchelper.form.CommentForm;
import com.ge.med.cchelper.popup.job.CheckinJob;
import com.ge.med.cchelper.util.ReourceHelper;

public class CheckinAction implements IObjectActionDelegate {
	private Shell shell;
	IFile currentIFile;


	
	public void run(IAction arg0) {

		if (MessageDialog.openConfirm(shell, "Confirm",
				"Are you sure to Checkin the file?")) {


			ReourceHelper resource = ReourceHelper.getResource();
			IProject project = ReourceHelper.getProject();
			CSession session = resource.getSession(project.getName());
			
			if (session==null||session.getHost() == null) {
				MessageDialog.openError(shell, "Error",
						"Please login clearcase server!");
				return;
			}

			if (currentIFile != null) {

				Display display = Display.getDefault();
				Shell shell = new Shell(display);
				CommentForm inst = new CommentForm(shell, SWT.NULL,"Checkin");
				inst.open();
				if(inst.isClose()){
					return;
				}
				
				CheckinJob synch = new CheckinJob("check in...",currentIFile,inst.getComments());
				synch.schedule();
			}

		}
	}

	
	public void selectionChanged(IAction arg0, ISelection arg1) {
		if (arg1 != null && arg1 instanceof IStructuredSelection) {
			IStructuredSelection obj = (IStructuredSelection) arg1;
			Object objs = obj.getFirstElement();
			if (objs instanceof IFile) {
				currentIFile = (IFile) objs;
				ReourceHelper.setProject(currentIFile.getProject());
				String filePath = currentIFile.getParent().getFullPath().toOSString();
				String vobPath = currentIFile.getProject().getFullPath().toOSString()+File.separator+Constants.VOB;
				if(!filePath.startsWith(vobPath)){
					arg0.setEnabled(false);
				}
			}else{
				arg0.setEnabled(false);
			}
		}
	}

	
	public void setActivePart(IAction arg0, IWorkbenchPart arg1) {
		shell = arg1.getSite().getShell();
	}

	public static void main(String[] strs) {

	}

}
